package mia.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mia.entity.CategoryEntity;
import mia.util.HibernateManager;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class CategoryEntityDAO {

	public static Map<String, CategoryEntity> getCategories() {
		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(CategoryEntity.class);
		List<CategoryEntity> list = crit.list();
		session.close();
		Map<String, CategoryEntity> map = new HashMap<String, CategoryEntity>();
		for (CategoryEntity cat : list) {
			map.put(cat.getName(), cat);
		}
		return map;
	}

	public static CategoryEntity getCategoryByName(String name) {

		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(CategoryEntity.class);
		crit.add(Restrictions.eq("name", name));
		@SuppressWarnings("unchecked")
		List<CategoryEntity> lista = crit.list();
		if (lista.size() > 0) {
			CategoryEntity result = lista.get(0);
			return result;
		} else
			return null;
	}

	public static CategoryEntity getCategoryById(Session session,
			int category_id) {

		Criteria crit = session.createCriteria(CategoryEntity.class);
		crit.add(Restrictions.eq("category_id", category_id));
		@SuppressWarnings("unchecked")
		List<CategoryEntity> lista = crit.list();
		if (lista.size() > 0) {
			CategoryEntity result = lista.get(0);

			return result;
		} else {
			return null;
		}
	}

	public static List<CategoryEntity> searchCategories(String name) {

		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(CategoryEntity.class);

		if (name != null && name != "")
			crit.add(Restrictions.like("CATEGORY_NAME", "%" + name + "%"));

		@SuppressWarnings("unchecked")
		List<CategoryEntity> list = crit.list();

		return list;
	}

	public static List<CategoryEntity> getCategoryByParent(Session session,
			CategoryEntity parent) {
		Criteria crit = session.createCriteria(CategoryEntity.class);

		crit.add(Restrictions.eq("parentCategory", parent.getCategory_id()));

		@SuppressWarnings("unchecked")
		List<CategoryEntity> list = crit.list();

		return list;
	}
}
